package com.example.ordersystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ordersystem.entity.Product;
import com.example.ordersystem.mapper.ProductMapper;
import com.example.ordersystem.service.ProductService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductMapper productMapper;

    @Override
    public Page<Product> page(Integer pageNum, Integer pageSize, String name) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(name), Product::getName, name)
                .orderByDesc(Product::getProductId);
        return productMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    public void save(Product product) {
        productMapper.insert(product);
    }

    @Override
    public void update(Product product) {
        productMapper.updateById(product);
    }

    @Override
    public void removeById(Integer id) {
        productMapper.deleteById(id);
    }

    @Override
    public Product getById(Integer id) {
        return productMapper.selectById(id);
    }

    @Override
    public void removeByName(String name) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getName, name);
        productMapper.delete(wrapper);
    }

    @Override
    public boolean existsByName(String name) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getName, name);
        return productMapper.selectCount(wrapper) > 0;
    }
}